/*
 * @Author: BuddyCoder
 * @Date: 2022-03-30 10:37:21
 * @LastEditTime: 2022-03-30 14:46:15
 * @LastEditors: BuddyCoder
 * @Description: 
 * @FilePath: /venom_log/src/appender.rs
 * MIT
 */
///
use chrono::{DateTime,  Utc,  Duration};
use log::{LevelFilter};
use std::time::SystemTime;
use std::ops::{Add, Sub};
use crate::appender::Command::CommandRecord;

/// LogAppender append logs 日志输出源
/// Appender will be running on single main thread,please do_log for new thread or new an Future
pub trait LogAppender: Send {
    /// this method use one coroutines run this(Multiple appenders share one Appender).
    /// so. if you want  access the network, you can launch a coroutine using go! (| | {});
    fn do_log(&self, record: &VenomLogRecord);

    fn type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Command {
    CommandRecord,
    CommandExit,
    /// Ensure that the log splitter forces splitting and saves the log
    CommandFlush,
}

#[derive(Clone, Debug)]
pub struct VenomLogRecord {
    ///指令
    pub command: Command,
    ///日志等级
    pub level: log::Level,
    ///标识
    pub target: String,
    ///参数
    pub args: String,
    ///模块路径
    pub module_path: String,
    ///文件
    pub file: String,
    //行数
    pub line: Option<u32>,
    //当前时间
    pub now: SystemTime,
    pub formated: String,
}

/// 格式化记录数据 format record data
pub trait RecordFormat: Send + Sync {
    fn do_format(&self, arg: &mut VenomLogRecord) -> String;
}

pub struct  VenomLogFormatRecord {
    pub duration: Duration,
    pub display_file: log::LevelFilter,
}

impl RecordFormat for VenomLogFormatRecord {
    fn do_format(&self, arg: &mut VenomLogRecord) -> String {
        if arg.command.eq(&CommandRecord) {
            let data;
            let now: DateTime<Utc> = chrono::DateTime::from(arg.now);
            let now = now.add(self.duration).naive_utc().to_string();
            if arg.level.to_level_filter() <= self.display_file {
                data = format!(
                    "{:26} {} {} - {}  {}:{}\n",
                    &now,
                    arg.level,
                    arg.module_path,
                    arg.args,
                    arg.file,
                    arg.line.unwrap_or_default()
                );
            } else {
                data = format!(
                    "{:26} {} {} - {}\n",
                    &now, arg.level, arg.module_path, arg.args
                );
            }
            return data;
        }
        return String::new();
    }
}

impl VenomLogFormatRecord {
    pub fn local_duration() -> Duration {
        let utc = chrono::Utc::now().naive_utc();
        let tz = chrono::Local::now().naive_local();
        tz.sub(utc)
    }

    pub fn new() -> VenomLogFormatRecord {
        Self {
            duration: Self::local_duration(),
            display_file: LevelFilter::Warn,
        }
    }
}